import 'whatwg-fetch'

function checkStatus(res) {
  // 登录接口如果密码错误返回500，在此处特殊处理一下
  if (
    (res.status > 200 && res.status < 400) ||
    (res.status == 500 && res.url.indexOf('login/acc/login') != -1)
  ) {
    return res
  }
  const err = new Error(res.statusText)
  err.response = res
  return Promise.reject(err)
}

function parseJSON(res) {
  return res.json()
}

function checkLogin(res) {
  if (res.retcode === 20012) {
    // 未登录
    window.location.href = `/wap/login?redirect=${encodeURIComponent(
      window.location.pathname + window.location.search
    )}`
  } else {
    return res
  }
}

export default {
  get(baseurl, query = {}, headers = {}) {
    let url = Object.keys(query).length == 0 ? baseurl : `${baseurl}?`
    Object.keys(query).forEach(key => {
      const val = encodeURIComponent(query[k])
      url += `${key}=${val}&`
    })
    url = url.replace(/&$/, '')
    const options = {
      method: 'GET',
      headers: new Headers(headers),
      mode: 'cors',
      credential: 'include'
    }
    return fetch(url, options)
      .then(checkStatus)
      .then(parseJSON)
      .then(checkLogin)
  },
  post(baseurl, formData, headers = {}) {
    const url = baseurl
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        ...headers
      },
      mode: 'cors',
      body: JSON.stringify(formData),
      credentials: 'include'
    }
    return fetch(url, options)
      .then(checkStatus)
      .then(parseJSON)
      .then(checkLogin)
  }
}